package chen.web.util.ubb.standard;

import chen.web.util.ubb.AbstractTag;
import chen.web.util.ubb.UbbTag;

/**
 * 表情标签，ubb示例：[emot=defaut,cry/],第一个参数是表情组，第二个参数是表情名称
 * 该标签解析需要提供一个表情url地址的模板，比如：http://www.abc.com/emot/?/?.gif
 * 第一个?表示组，第二个?表示名称。解析后的表情地址：http://www.abc.com/emot/default/cry.gif
 * @author chen
 *
 */
public class EmotionTag extends AbstractTag {

	private static final String TagName = "emot";
	public static final String Regex = "?";
	
	private String urlRegex = null;
	public EmotionTag(){}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return TagName;
	}

	@Override
	public void toHtml(StringBuilder sb) {
		// TODO Auto-generated method stub
		String property = getProperty();
		if(property != null && property.length() > 0){
			int i = property.indexOf(',');
			if(i > 0){
				String group = property.substring(0, i);
				String name = property.substring(i+1);
				sb.append("<img src=\"");
				appendUrl(group, name, sb);
				sb.append("\"/>");
				innerHTML(sb);
				return;
			}
		} 
		super.ignore(sb);
	}
	
	
	private String front = null;
	private String middle = null;
	private String end = null;
	
	private void initSegment(){
		int groupIndex = urlRegex.indexOf(Regex);
		int nameIndex = urlRegex.indexOf(Regex, groupIndex + Regex.length());
		front = urlRegex.substring(0, groupIndex);
		middle = urlRegex.substring(groupIndex+Regex.length(), nameIndex);
		end = urlRegex.substring(nameIndex + Regex.length());
	}
	
	private void appendUrl(String group, String name, StringBuilder sb){
		sb.append(front).append(group).append(middle).append(name).append(end);
	}
	
	@Override
	public UbbTag newInstance() {
		// TODO Auto-generated method stub
		EmotionTag tag = new EmotionTag();
		tag.urlRegex = this.urlRegex;
		tag.front = this.front;
		tag.middle = this.middle;
		tag.end = this.end;
		return tag;
	}

	public String getUrlRegex() {
		return urlRegex;
	}
	public void setUrlRegex(String urlRegex) {
		this.urlRegex = urlRegex;
		initSegment();
	}

	@Override
	protected void toUbb(StringBuilder sb, boolean escape) {
		// TODO Auto-generated method stub
		sb.append('[').append(getName());
		String property = super.getProperty();
		if(property != null){
			sb.append('=').append(property);
		}
		sb.append("/]");
		innerUbb(sb, escape);
	}
	
}
